package com.api.oa.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.api.oa.model.entity.YQCase;
import com.api.oa.model.entity.YQWork;
import com.api.oa.services.YQCaseService;
import com.api.shopapi.controller.BaseController;
import com.api.shopapi.entity.MyResult;
import org.apache.commons.fileupload.FileUpload;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@RestController
@RequestMapping("/yq/yQCase")
public class YQCaseController extends BaseController {

    @Autowired
    private YQCaseService iYQCaseService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public MyResult Add(@RequestBody YQCase entity) {
        try {
            return iYQCaseService.add(entity) == 1 ? success(entity) : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }

    /**
     * 上传病例
     *
     * @param file
     * @param requestOrder
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public MyResult Add(@RequestParam("file") MultipartFile file, @RequestParam("requestOrder") String requestOrder) {
        try {
            YQCase yqWork = new YQCase();
            yqWork.setCreatedAt(DateUtil.date());
            yqWork.setRequestOrder(requestOrder);
            File file1 = new File(this.rootPath +"/files"+file.getOriginalFilename());
            file.transferTo(file1);
            HttpResponse response = HttpRequest.post("http://47.104.134.89:8088/upload/UploadifyAvatarServlet")
                    .form("userId", DateUtil.currentSeconds())
                    .form("version", "1")
                    .form("file",file1)
                    .execute();
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONObject data = jsonObject.getJSONObject("data");
            yqWork.setCaseUrl(data.getStr("oUrl"));
            FileUtil.del(file1);
            return  iYQCaseService.add(yqWork) == 1 ? success(data.getStr("oUrl")) : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }

    private String getFileUrl() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String fileUrl = "http://" + address.getHostAddress() + ":" + port;
            return fileUrl;
        } catch (UnknownHostException e) {
            return "";
        }
    }


    @RequestMapping(value = "/remove/{id}", method = RequestMethod.POST)
    public MyResult remove(@PathVariable Long id) {
        try {
            iYQCaseService.remove(id);
            return success("删除成功!");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public MyResult update(@RequestBody YQCase entity) {
        try {
            return iYQCaseService.update(entity) == 1 ? success("操作成功") : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MyResult list(@RequestParam(defaultValue = "0") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(required = false) String requestOrder) {
        try {
            return success(iYQCaseService.list(requestOrder, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
    public MyResult one(@PathVariable Long id) {
        try {
            return success(id == null ? null : iYQCaseService.one(id));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "/read/{id}", method = RequestMethod.GET,produces = "image/*")
    public void read(@PathVariable Long id, HttpServletResponse res) throws IOException {
        YQCase one = iYQCaseService.one(id);
        String name = one.getCaseUrl().split("/")[2];
        res.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(StandardCharsets.UTF_8), "ISO8859_1"));
        res.getOutputStream().write(FileUtil.readBytes(this.rootPath + "/" + one.getCaseUrl()));
    }
}
